package com.mallcloud.mall.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mallcloud.mall.admin.api.entity.SysTenant;
import com.mallcloud.mall.admin.service.SysTenantService;
import com.mallcloud.mall.common.core.constant.CacheConstants;
import com.mallcloud.mall.common.core.util.R;
import com.mallcloud.mall.common.data.tenant.TenantContextHolder;
import com.mallcloud.mall.common.security.annotation.Inner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "租户管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/tenant")
public class SysTenantController {

	private final SysTenantService sysTenantService;

	@ApiOperation("分页查询")
	@GetMapping("/page")
	public R<IPage<SysTenant>> getSysTenantPage(Page page, SysTenant sysTenant) {
		return R.ok(sysTenantService.page(page, Wrappers.query(sysTenant)));
	}

	@ApiOperation("查询租户信息")
	@GetMapping
	public R<List<SysTenant>> getByObj(SysTenant tenant) {
		return R.ok(sysTenantService.list(Wrappers.query(tenant)));
	}

	@ApiOperation("新增租户")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('admin_systenant_add')")
	@CacheEvict(value = CacheConstants.TENANT_DETAILS, allEntries = true)
	public R<Boolean> save(@RequestBody SysTenant sysTenant) {
		return R.ok(sysTenantService.saveTenant(sysTenant));
	}

	@ApiOperation("修改租户")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('admin_systenant_edit')")
	@CacheEvict(value = CacheConstants.TENANT_DETAILS, allEntries = true)
	public R<Boolean> updateById(@RequestBody SysTenant sysTenant) {
		return R.ok(sysTenantService.updateById(sysTenant));
	}

	@ApiOperation("通过id删除租户")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('admin_systenant_del')")
	@CacheEvict(value = CacheConstants.TENANT_DETAILS, allEntries = true)
	public R<Boolean> removeById(@PathVariable Long id) {
		return R.ok(sysTenantService.removeById(id));
	}

	@ApiOperation("查询全部有效的租户")
	@Inner(value = false)
	@GetMapping("/list")
	public R<List<SysTenant>> list() {
		return R.ok(sysTenantService.getNormalTenant().stream()
				.filter(tenant -> tenant.getStartTime().before(new Date()))
				.filter(tenant -> tenant.getEndTime().after(new Date()))
				.collect(Collectors.toList())
		);
	}

	@ApiOperation("查询全部有效的租户")
	@Inner(value = false)
	@GetMapping("/info")
	public R<SysTenant> info() {
		return R.ok(sysTenantService.getNormalTenant().stream()
				.filter(tenant -> tenant.getId().equals(TenantContextHolder.getTenantId()))
				.findFirst().orElse(null)
		);
	}

}
